//
//  HJFirstPageHelper.m
//  SmartHome
//
//  Created by huiju on 15/3/26.
//  Copyright (c) 2015年 huiju. All rights reserved.
//
#import "HJFirstPageHelper.h"
//#import "ChangeRootNavigationController.h"
#import "AppDelegate.h"
#import "UserInfoHelper.h"
//#import "HJDoorShortKeyAPI.h"
//#import <RDVTabBarItem.h>

@implementation HJFirstPageHelper
Byte userIdByte[4];

//首页WiFi开门
-(void)wifiOpenDoorControl:(NSData *)data tag:(NSInteger)tag{
    self.asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    NSError *error = nil;
    //连接AP的IP地址
    if (![self.asyncSocket connectToHost:@"10.10.100.254" onPort:8899 error:&error]) {
        NSLog(@"Unable to connect to due to invalid configuration: %@",error);
    }
    [self.asyncSocket writeData:data withTimeout:5.0 tag:tag];
    [self.asyncSocket readDataWithTimeout:5.0 tag:tag];
}

#pragma mark-- socket dele
- (void)socket:(GCDAsyncSocket *)sock
didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    NSLog(@"Socket did accept new socket");
}

- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Cool, I'm connected! That was easy.");
}

- (void)socket:(GCDAsyncSocket *)sender didWriteDataWithTag:(long)tag{
    if (tag == 1) {
    }
}


#pragma mark -- socket的回调
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
    //WIFI开门
    if (tag == 0) {
        //为AppDelegate中发的请求
        if (data != NULL) {
            Byte *backByte = (Byte *)[data bytes];
            //为获取门口机ID
            if (((backByte[1]&0xff) == 10 && data.length == 12) || ((backByte[1]&0xff) == 10 && data.length == 24)) {
                //为门口机返回的数据，进行一下操作
                if (backByte[4] == userIdByte[0] && backByte[5] == userIdByte[1] && backByte[6] == userIdByte[2] && backByte[7] == userIdByte[3]) {
                    [self.delegate didWiFiReturnWith:data];
                }
            }
        }
    }else{
        //为其他发的请求
        if (data != NULL) {
            Byte *backByte = (Byte *)[data bytes];
            //为获取门口机ID
            if (((backByte[1]&0xff) == 10 && data.length == 12) || data.length == 9) {
                //为门口机返回的数据，进行一下操作
                if (backByte[4] == userIdByte[0] && backByte[5] == userIdByte[1] && backByte[6] == userIdByte[2] && backByte[7] == userIdByte[3]) {
                    [self.delegate didWiFiReturnWith:data];
                }
            }
        }
    }
    [self.asyncSocket disconnect];
}
- (void)socket:(GCDAsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{
    NSLog(@"partiallength%lu",(unsigned long)partialLength);
    [self.asyncSocket readDataToLength:partialLength withTimeout:-1.0 tag:tag];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"error:%@",err);
    if (err != nil) {
//        [SVProgressHUD dismiss];
    }
}

//WIFI开门请求，已确认是否能够开门
-(void)wifiOpenRequse:(NSInteger)tag{
    NSDictionary *userInfoDic = [[UserInfoHelper share] getUserInfoAndBindInfo];
    if (userInfoDic != nil) {
        NSString *userId = [NSString stringWithFormat:@"%@",[[UserInfoHelper share] getUserId]];
        NSInteger datai = [userId integerValue];
        NSData *dataMsg = [NSData dataWithBytes: &datai length: sizeof(datai)];
        //        Byte *byte = (Byte *)[data bytes];
        Byte *byteMsg = (Byte *)[dataMsg bytes];
        //发送的内容
        for (int i = 0; i < 4; i++) {
            userIdByte[i] = 0x00;
        }
        Byte verify = [[UserInfoHelper share] getVerify:0xc1 tag:dataMsg data:0x00];
        Byte message[20];
        for (int j = 0; j < 9; j++) {
            message[j] = 0x00;
        }
        message[0] = '\x00';
        message[1] = '\x07';
        message[2] = verify;
        message[3] = '\xc1';
        for (int i = 0; i < 4; i++) {
            message[i+4] = byteMsg[i];
            userIdByte[i] = byteMsg[i];
        }
        message[8] = '\x00';
        NSMutableData *msgData = [[NSMutableData alloc] initWithCapacity:64];
        NSData *requestData = [[NSData alloc] initWithBytes:message length:9];
        [msgData appendData:requestData];
        [self wifiOpenDoorControl:msgData tag:tag];
    }
}
//在确认是WIFI开门之后，开门
-(void)openTheDoor
{
//    [SVProgressHUD show];
    //WiFi开门
    NSString *userId = [NSString stringWithFormat:@"%@",[[UserInfoHelper share] getUserId]];
    NSData *data = [userId dataUsingEncoding:NSUTF8StringEncoding];
    NSInteger datai = [userId integerValue];
    NSData *dataMsg = [NSData dataWithBytes: &datai length: sizeof(datai)];
    //        Byte *byte = (Byte *)[data bytes];
    Byte *byteMsg = (Byte *)[dataMsg bytes];
    //发送的内容
    for (int i = 0; i < 4; i++) {
        userIdByte[i] = 0x00;
    }
    Byte verify = [[UserInfoHelper share] getVerify:0xc4 tag:data data:dataMsg];
    NSInteger index = 8+(data.length);
    NSInteger msgLenght = 6+data.length;
    Byte message[20];
    for (int j = 0; j < index; j++) {
        message[j] = 0x00;
    }
    message[0] = '\x00';
    message[1] = (Byte)msgLenght;
    message[2] = verify;
    message[3] = '\xc4';
    for (int i = 0; i < 4; i++) {
        message[i+4] = byteMsg[i];
        userIdByte[i] = byteMsg[i];
    }
    NSMutableData *msgData = [[NSMutableData alloc] initWithCapacity:64];
    NSData *requestData = [[NSData alloc] initWithBytes:message length:8];
    [msgData appendData:requestData];
    [msgData appendData:data];
    [self wifiOpenDoorControl:msgData tag:[userId integerValue]];
}

//当为WIFI开门时，需要保存开门的记录
-(void)saveOpenRecord:(NSString *)doorId
{
//    NSString *villageId = [[UserInfoHelper share] getSelectVillageId];
//    NSMutableArray *doorList = [HJDoorShortKeyAPI getFirstPageClockMsg:villageId];
//    int count = 0;
//    for (int i = 0; i < [doorList count]; i++) {
//        NewDoorData *doorMsg = [doorList objectAtIndex:i];
//        if ([doorId isEqualToString:doorMsg.devId]) {
//            break;
//        }
//        count++;
//    }
//    NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
//    if (count == [doorList count]) {
//        //为其他小区
//        [userInfo setValue:[NSString stringWithFormat:@"%d",0] forKey:@"localDoorMsg"];
//    }else{
//        //为本小区
//        [userInfo setValue:[NSString stringWithFormat:@"%d",count] forKey:@"localDoorMsg"];
//    }
//    [userInfo synchronize];
}

//当WIFI开门时，而又不是连接的该小区时，需要切换小区
-(void)changCommunityWiFiOpenDoor:(NSString *)vid{
    //首先//保存开门记录，下次进来时跳转到这里
    NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
    [userInfo setValue:[NSString stringWithFormat:@"%d",0] forKey:@"localDoorMsg"];
    [userInfo synchronize];
    //根据小区vid在本地查找小区内容
    NSDictionary *userInfoDic = [[UserInfoHelper share] getUserInfoAndBindInfo];
    NSArray *bindArr = [userInfoDic valueForKey:@"bind"];
    for (int i = 0; i < [bindArr count]; i++) {
        NSDictionary *bindMsg = [bindArr objectAtIndex:i];
        if ([vid integerValue] == [[bindMsg valueForKey:@"vid"] integerValue]) {
            NSDictionary *dic = @{@"vid":vid,@"des":[bindMsg valueForKey:@"des"],@"hid":[bindMsg valueForKey:@"hid"],@"det":[bindMsg valueForKey:@"det"]};
            // 存放到KUserInfo里面
            [[UserInfoHelper share] saveSelectVillageDic:dic];
            //最后发送，更新的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeCommunity" object:nil];
            break;
        }
    }
}
@end